package com.yups.utils;

/**
 * 计算距离工具类
 *
 * @author 于鹏生
 */
public class GeoUtils {
	public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
		double radlat1 = Math.toRadians(lat1);
		double radlat2 = Math.toRadians(lat2);
		double a = radlat1 - radlat2;
		double b = Math.toRadians(lng1) - Math.toRadians(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radlat1)
				* Math.cos(radlat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378137.0;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	/**
	 * 计算 tp值
	 *
	 * @param curpoint     坐标点 1
	 * @param relatedpoint 坐标点 2
	 * @param isgeography  是否是地理坐标 false为2d坐标
	 * @return tp 值
	 */
	public static double getDirangle(Point curpoint, Point relatedpoint,
									 boolean isgeography) {
		double result = 0;
		if (isgeography) {
			double y2 = Math.toRadians(relatedpoint.getLat());
			double y1 = Math.toRadians(curpoint.getLat());
			double alpha =
					Math.atan2(relatedpoint.getLat() - curpoint.getLat(),
							(relatedpoint.getLng() - curpoint.getLng())
									* Math.cos((y2 - y1) / 2));
			double delta = alpha < 0 ? (2 * Math.PI + alpha) : alpha;
			result = Math.toDegrees(delta);
		} else {
			double alpha = Math.atan2(relatedpoint.getLat() - curpoint.getLat(),
					relatedpoint.getLng() - curpoint.getLng());
			double delta = alpha < 0 ? (2 * Math.PI + alpha) : alpha;
			result = Math.toDegrees(delta);
		}
		return result;
	}

	class Point {
		private double lat;
		private double lng;

		public double getLat() {
			return lat;
		}

		public void setLat(double lat) {
			this.lat = lat;
		}

		public double getLng() {
			return lng;
		}

		public void setLng(double lng) {
			this.lng = lng;
		}
	}
}
